package com.woniu.adapter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.WarehousePoMapper;
import com.woniu.outlet.po.WarehousePo;
import com.woniu.outlet.rabbitmq.MessageRepo;
import com.woniu.outlet.redis.RedisRepo;
import com.woniu.utils.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class WarehouseAdapter {

    @Autowired
    private WarehousePoMapper warehousePoMapper;

    @Autowired
    private RedisRepo redisRepo;

    @Autowired
    private MessageRepo messageRepo;


    public List<WarehousePo> findWarehouses() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("warehouse:list");
        List<WarehousePo> lists = new ArrayList<>();
        if (!StringUtils.isEmpty(str)) {
            lists = mapper.readValue(str, new TypeReference<List<WarehousePo>>() {
            });
            return lists;
        }
        lists = warehousePoMapper.selectByExample(null);
        //存到redis
        redisRepo.saveRedisRepo("warehouse:list",mapper.writeValueAsString(lists));
        return lists;
    }

    public WarehousePo getWarehouseById(Long id) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("warehouse:" + id);
        WarehousePo warehousePo = null;
        if (!StringUtils.isEmpty(str)) {
            warehousePo = mapper.readValue(str, new TypeReference<WarehousePo>() {
            });
            return warehousePo;
        }
        warehousePo = warehousePoMapper.selectByPrimaryKey(id);
        //存到redis
        redisRepo.saveRedisRepo("warehouse:"+id,mapper.writeValueAsString(warehousePo));
        return warehousePo;
    }

    public void addWarehousePo(WarehousePo warehousePo){
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator();
        long id = snowflakeIdGenerator.nextId();
        warehousePo.setWarehouseCode("CKBM"+id);
        warehousePoMapper.insert(warehousePo);
        redisRepo.deleteRedisRepo("warehouse:list");

    }

    public void updateWarehousePo(WarehousePo warehousePo){
        warehousePoMapper.updateByPrimaryKeySelective(warehousePo);
        redisRepo.deleteRedisRepo("warehouse:list");
    }

    public void deleteWarehousePoById(Long id){
        warehousePoMapper.deleteByPrimaryKey(id);
        redisRepo.deleteRedisRepo("warehouse:list");
    }
}
